#include "board.h"
#include "hole.h"
#include "rock.h"
#include <QString>
#include <QDebug>

Board::Board(QObject *parent)
    : holeRadius_(24.0)
    , rockRadius_(20.0)
    , padding_(24.0)
    , rows(9)
    , cols(9)
    , QGraphicsScene(parent)
{
    boardMap_ =
    "   @@@   "
    "   @@@   "
    "   @@@   "
    "@@@@@@@@@"
    "@@@@O@@@@"
    "@@@@@@@@@"
    "   @@@   "
    "   @@@   "
    "   @@@   ";

    draw();

    setSceneRect(0, 0, 420, 420);
}

void Board::draw() {
    if (boardMap_.length() != rows * cols) {
        qCritical() << "Wrong count of elements during initializing boardMap";
    }

    for(int i = 0; i < rows; ++i) {
        for(int j = 0; j < cols; ++j) {
            char c = boardMap_[i*cols + j].toAscii();
            Hole* hole = 0;
            switch(c) {
            case '@':
                hole = createHole(i, j);
                holes_.push_back(hole);
                createRock(hole);
                break;
            case 'O':
                holes_.push_back(createHole(i, j));
                break;

            default:
                holes_.push_back(0);
                break;
            }
        }
    }
}

void Board::createRock(Hole* hole) {
    Rock* rock = new Rock(hole, rockRadius_, rockRadius_);
    qreal shift = (holeRadius_-rockRadius_) / 2;
    rock->setPos(hole->x() + shift, hole->y() + shift);
    addItem(rock);
}

Hole* Board::createHole(int row, int col) {
    Hole* hole = new Hole(this, holeRadius_, holeRadius_);
    hole->setCoords(row, col);
    hole->setPos(col*(holeRadius_ + padding_), row*(holeRadius_ + padding_));
    hole->setZValue(-1);
    addItem(hole);
    return hole;
}

Hole* Board::getHole(int row, int col) {
    qDebug() << holes_[row*cols + col]->row() << " " << holes_[row*cols + col]->col();
    qDebug() << holes_[row*cols + col]->hasRock();
    return holes_[row*cols + col];
}

bool Board::removeRock(int row, int col) {
    Rock* rock = getHole(row, col)->getRock();
    if(rock) {
        qDebug() << "Removing rock from hole";
        getHole(row, col)->setHasRock(false);
        removeItem(rock);
        return true;
    } else {
        return false;
    }
}
